<template>
  <a-card>
    <p style="font-size: 18px; text-align: center">生产材料出库单</p>
    <br />
    <!-- 单据 -->
    <a-form-model ref="ruleForm" :model="Form" v-bind="layout" :rules="rules"
      ><!-- 顶部的信息 -->
      <a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据号">
            <a-input
              style="border: 0"
              v-model="Form.document"
              disabled
            ></a-input>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="单据日期">
            <a-date-picker
              v-model="Form.document_date"
              type="date"
              placeholder="请选择时间"
              style="width: 100%"
              @change="
                (a, b) => {
                  this.Form.a = a;
                  this.Form.document_date = b;
                  this.Form.balance = b;
                  this.DataSource.forEach((item, index) => {
                    this.DataSource[index].deliveryDate = b;
                  });
                }
              "
            />
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="仓库名称" prop="depotName">
            <a-select
              v-model="Form.depotName"
              showSearch
              style="width: 100%"
              @change="setdataSourceDepartment"
              disabled
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="item.depotNo + '|' + item.depotName"
                >{{ item.depotNo }}{{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="产成品仓库" prop="finishedProductDepot">
            <a-select
              placeholder=""
              v-model="Form.finishedProductDepot"
              @change="setFinishProduct"
            >
              <a-select-option
                v-for="item in storageList"
                :key="item.depotId"
                :value="item.depotNo + '|' + item.depotName"
              >
                {{ item.depotNo }}{{ item.depotName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="收发类别" prop="sendReceiveType">
            <a-select
              v-model="Form.sendReceiveType"
              @change="getSendReceiveTypeId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="(item, index) in SendReceiveList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="库存组织" prop="pk_calbody">
            <a-select
              v-model="Form.pk_calbody"
              @change="getpk_calbodyId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in InventoryOrganizationList"
                :key="item.pkCalbody"
                :value="item.bodycode + '|' + item.bodyname"
              >
                {{ item.bodycode }}
                {{ item.bodyname }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="领料员">
            <a-select
              v-model="Form.picker"
              @change="getPickerId"
              @search="searchUserInfoList"
              showSearch
              style="width: 100%"
              disabled
            >
              <a-select-option
                v-for="item in UserList"
                :key="item.userId"
                :value="item.workNo + '|' + item.userName"
              >
                {{ item.workNo }} {{ item.userName }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="公司" prop="pk_corp">
            <a-input v-model="Form.pk_corp" disabled></a-input>
            <!-- <a-tree-select
              v-model="Form.pk_corp"
              show-search
              style="width: 100%"
              allow-clear
              :tree-data="pk_corpList"
              @change="getpk_corpId"
            >
            </a-tree-select> -->
          </a-form-model-item>
        </a-col>

        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="产成品分类" prop="finishGoodsType">
            <a-tree-select
              v-model="Form.finishGoodsType"
              @change="setFinishGoodsType"
              :tree-data="finishGoodsTypeList"
              style="width: 100%"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="农户" ref="farmerName" prop="farmerName">
            <a-select
              v-model="Form.farmerName"
              @change="getfarmerId"
              showSearch
              style="width: 100%"
            >
              <a-select-option
                v-for="item in farmerList"
                :key="item.id"
                :value="item.No + '|' + item.name + '|' + item.id"
              >
                {{ item.No }} {{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="所属分厂" prop="ownedBranch">
            <a-tree-select
              v-model="Form.ownedBranch"
              style="width: 100%"
              :tree-data="ownedBranchList"
              showSearch
              @change="changeTreeNode"
              disabled
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>
        <a-col :xl="6" :lg="6" :md="8" :sm="24" :xs="24">
          <a-form-model-item label="部门" ref="deptIdName" prop="deptIdName">
            <a-input
              v-model="Form.deptIdName"
              @change="onChangeBumen"
              style="width: 100%"
              disabled
            >
            </a-input>
          </a-form-model-item>
        </a-col>
      </a-row>
    </a-form-model>

    <!-- 生成原单按钮组件 -->
    <productPickingInfo @origin-data="getOriginData"></productPickingInfo>

    <!-- //TODO: -->
    <!-- 单据对应表格 -->
    <a-table
      :columns="columns"
      :data-source="DataSource"
      style="margin-top: 10px"
      :pagination="false"
      :scroll="{ x: 4000 }"
      :rowkey="randomKey"
    >
      <!-- 所属仓库 -->
      <span slot="storageUnit" slot-scope="text, record">
        <a-select
          v-model="record.storageUnit"
          @change="getstorageUnitId(record.key)"
          style="width: 100%"
          showSearch
        >
          <a-select-option
            v-for="item in storageList"
            :key="item.depotNo"
            :value="item.depotNo + '|' + item.depotName"
          >
            {{ item.depotNo }} {{ item.depotName }}
          </a-select-option>
        </a-select>
      </span>
      <!-- 仓库编码 -->
      <span slot="depotNo" slot-scope="text, record">
        <a-select
          v-model="record.depotNo"
          showSearch
          style="width: 100%"
          @change="setGoodsList(record.key)"
        >
          <a-select-option
            v-for="item in storageList"
            :key="item.depotNo"
            :value="item.depotNo + '|' + item.depotName"
          >
            {{ item.depotNo }} {{ item.depotName }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 库位 -->
      <span slot="depotLocation" slot-scope="text, record">
        <a-select
          v-model="record.depotLocation"
          style="width: 100%"
          :tree-data="record.positionList"
          allow-clear
        ></a-select>
      </span>
      <!-- 仓位 -->
      <span slot="position" slot-scope="text, record">
        <a-tree-select
          v-model="record.position"
          style="width: 100%"
          :tree-data="record.positionList"
          allow-clear
        ></a-tree-select>
      </span>

      <!-- 存货编码 -->
      <span slot="inventoryName" slot-scope="text, record">
        <a-select
          v-model="record.inventoryName"
          style="width: 100%"
          @change="getInventoryInfo(record.key)"
          @search="handleInventoryInfoSearch"
          showSearch
        >
          <a-select-option
            v-for="item in goodsList"
            :key="item.inventoryId"
            :value="
              item.inventoryNo +
              '|' +
              item.inventoryName +
              '|' +
              item.standardModel +
              '|' +
              item.unit
            "
          >
            {{ item.inventoryNo }} {{ item.inventoryName }}
            {{ item.standardModel }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 辅助单位 -->
      <!-- <span slot="auxiliary_unit" slot-scope="text, record">
        <a-select
          v-model="record.auxiliary_unit"
          style="width: 100%"
          @change="disableUnit(record.key)"
        >
          <a-select-option
            v-for="item in Auxiliary_Unitlist"
            :key="item.title"
            :value="item.value"
          >
            {{ item.title }}
          </a-select-option>
        </a-select>
      </span> -->

      <!-- 数量 -->
      <span slot="quantity" slot-scope="text, record">
        <a-input-number
          v-model="record.quantity"
          :min="0"
          :precision="precision"
        />
      </span>

      <!-- 批次号 -->
      <span slot="batchNumber" slot-scope="text, record">
        <a-select
          v-model="record.batchNumber"
          style="width: 100%"
          @change="getBatchNumberInfo(record.key)"
        >
          <a-select-option
            v-for="(item, index) in record.BatchList"
            :key="index"
            :value="item"
          >
            {{ item }}
          </a-select-option>
        </a-select>
      </span>

      <!-- 产成品分类 -->
      <!-- <span slot="finishedProductType" slot-scope="text, record">
        <a-tree-select
          :tree-data="finishGoodsTypeList"
          @change="getFinishGoodsTypeId(record.key)"
          v-model="record.finishedProductType"
          style="width: 100%"
        >
        </a-tree-select>
      </span> -->

      <!-- 出库日期 -->
      <span slot="deliveryDate" slot-scope="text, record">
        <a-date-picker
          @change="formatDeliveryDate(record.key)"
          v-model="record.deliveryDate"
          type="date"
          placeholder="请选择时间"
          style="width: 100%"
          disabled
        />
      </span>
      <!-- 出菇领料金额 -->
      <span slot="amountOfFruitPicking" slot-scope="text, record">
        <a-input-number
          v-model="record.amountOfFruitPicking"
          :min="0"
          :precision="amountPrecision"
        />
      </span>

      <!-- 货架-->
      <span slot="goodsShelves" slot-scope="text, record">
        <a @click="shelfDetails(record)">详情</a>
      </span>
      <!-- 备注 -->
      <span slot="remark" slot-scope="text, record">
        <a-input v-model="record.remark"> </a-input>
      </span>

      <template slot="action" slot-scope="text, record">
        <span>
          <a @click="getGoodsShelves(record)">选择货架 </a>
        </span>
        <span v-if="record.isNew">
          <a @click="cancle(record.key)">| 取消</a>
        </span>
        <!-- <span v-else>
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="Delete(record.id)"
          >
            <template slot="title">
              <p>确定删除？</p>
            </template>
            <a type="danger"> 删除 </a>
          </a-popconfirm>
        </span> -->
      </template>
    </a-table>
    <a-button
      style="width: 100%; margin-top: 16px; margin-bottom: 8px"
      type="dashed"
      icon="plus"
      @click="newMember"
      >添加</a-button
    >

    <div style="margin-top: 20px">
      <!-- 单据 -->
      <a-form-model
        :model="Form"
        v-bind="layout"
        :rules="rules2"
        ref="ruleForm2"
        ><!-- 顶部的信息 -->
        <a-row>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="库管员" prop="cwhsmanager">
              <a-select
                v-model="Form.cwhsmanager"
                showSearch
                style="width: 100%"
                @search="searchUserInfoList"
                @change="changecwhsmanager"
              >
                <a-select-option
                  v-for="item in UserList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>
          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="负责人" prop="responsiblePerson">
              <a-select
                v-model="Form.responsiblePerson"
                style="width: 100%"
                showSearch
                @change="setResponsible_person"
              >
                <a-select-option
                  v-for="item in responsiblePersonList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核人" prop="inspector">
              <a-select
                v-model="Form.inspector"
                showSearch
                @change="setInspector"
                style="width: 100%"
              >
                <a-select-option
                  v-for="item in inspectorList"
                  :key="item.userId"
                  :value="item.workNo + '|' + item.userName"
                >
                  {{ item.workNo }} {{ item.userName }}
                </a-select-option>
              </a-select>
            </a-form-model-item>
          </a-col>

          <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
            <a-form-model-item label="审核日期" prop="">
              <a-date-picker
                v-model="Form.balance"
                type="date"
                style="width: 100%"
                disabled
              />
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-col :xl="6" :lg="6" :md="12" :sm="24" :xs="24">
          <a-form-model-item label="制单人" prop="">
            <a-input disabled v-model="Form.singleProducer"> </a-input>
          </a-form-model-item>
        </a-col>
      </a-form-model>

      <!-- 提交按钮组  -->
      <div style="margin-top: 20px">
        <center>
          <!-- <a-button type="primary" style="margin-right: 20px"> 打印 </a-button> -->
          <a-button
            @click="Save"
            style="margin-right: 20px"
            :disabled="isAntiAudit"
          >
            保存
          </a-button>

          <a-button
            style="margin-right: 20px"
            @click="Check"
            :disabled="!isAntiAudit"
          >
            审核
          </a-button>

          
        </center>
      </div>
    </div>
    <GoodsShelvesInfo
      :goodsShelvesTag="goodsShelvesTag"
      :tableKey="tableKey"
      :position="position"
      ref="goodShelvesInfo"
      @close-goodShelveInfo="closeGoodsShelves"
      @get-goodShelveInfo="getGoodShelveInfo"
    ></GoodsShelvesInfo>
    <a-modal
      title="货架详情"
      :visible="shelfWindow"
      @ok="handleOk_shelfDetails"
      width="50%"
      @cancel="handleCancel_shelfDetails"
    >
      {{ this.saveShelfDetails }}
    </a-modal>
  </a-card>
</template>

<script>
import axios from "axios";
import productPickingInfo from "@/components/common/productPickingInfo";
import GoodsShelvesInfo from "../../components/common/GoodsShelvesInfo"; //
import { CommonAjax } from "@/services/modules/common";
const comHttp = new CommonAjax(); // 公用接口

// import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao.js";
// const zdbHttp = new ZiDianBiaoHttp(); // 字典表

import moment from "moment";
import { mapState, mapGetters } from "vuex";
// import getOverlappingDaysInIntervals from "date-fns/esm/fp/getOverlappingDaysInIntervals";

// 1. 导入
// import footerCommonBar from "../../components/common/footerCommonBar";

// 规则

// 物品信息表格
const columns = [
  {
    title: "序号",
    dataIndex: "key",
    key: "key",
    align: "center",
  },

  {
    title: "仓库编码",
    dataIndex: "depotNo",
    key: "depotNo",
    align: "center",
    width: "7%",
    scopedSlots: { customRender: "depotNo" },
  },
  {
    title: "仓库名称",
    dataIndex: "depotName",
    key: "depotName",
    align: "center",
  },
  // {
  //   title: "库位",
  //   dataIndex: "depotLocation",
  //   key: "depotLocation",
  //   align: "center",
  //   scopedSlots: { customRender: "depotLocation" },
  // },
  {
    title: "仓位",
    dataIndex: "position",
    key: "position",
    align: "center",
    scopedSlots: { customRender: "position" },
  },
  {
    title: "存货编码",
    dataIndex: "inventoryNo",
    key: "inventoryNo",
    align: "center",

    scopedSlots: { customRender: "inventoryNo" },
  },
  {
    title: "存货名称",
    dataIndex: "inventoryName",
    key: "inventoryName",
    width: "10%",
    align: "center",
    scopedSlots: { customRender: "inventoryName" },
  },
  {
    title: "规格型号",
    dataIndex: "standardModel",
    key: "standardModel",
    align: "center",
  },
  {
    title: "单位",
    key: "unit",
    dataIndex: "unit",
    align: "center",
  },
  {
    title: "批次号",
    key: "batchNumber",
    dataIndex: "batchNumber",
    align: "center",
    scopedSlots: { customRender: "batchNumber" },
  },
  {
    title: "现存数量",
    key: "existingQuantity",
    dataIndex: "existingQuantity",
    align: "center",
    scopedSlots: { customRender: "existingQuantity" },
  },
  {
    title: "数量",
    key: "quantity",
    dataIndex: "quantity",
    align: "center",
    scopedSlots: { customRender: "quantity" },
  },
  {
    title: "单价",
    key: "unitPrice",
    dataIndex: "unitPrice",
    align: "center",
    scopedSlots: { customRender: "unitPrice" },
  },
  {
    title: "金额",
    key: "money",
    dataIndex: "money",
    align: "center",
    scopedSlots: { customRender: "money" },
  },
  {
    title: "源单单号",
    key: "sourceNumber",
    dataIndex: "sourceNumber",
    align: "center",
  },

  // {
  //   title: "产成品分类",
  //   key: "finishedProductType",
  //   dataIndex: "finishedProductType",
  //   align: "center",
  //   scopedSlots: { customRender: "finishedProductType" },
  // },
  {
    title: "出库日期",
    key: "deliveryDate",
    dataIndex: "deliveryDate",
    align: "center",
    // defaultFilteredValue: moment().format("YYYY-MM-DD"),
    scopedSlots: { customRender: "deliveryDate" },
  },
  {
    title: "出菇领料金额",
    key: "amountOfFruitPicking",
    dataIndex: "amountOfFruitPicking",
    align: "center",
    scopedSlots: { customRender: "amountOfFruitPicking" },
  },
  {
    title: "货架",
    dataIndex: "goodsShelves",
    key: "goodsShelves",
    align: "center",
    scopedSlots: { customRender: "goodsShelves" },
  },

  {
    title: "备注",
    dataIndex: "remark",
    key: "remark",
    align: "center",
    scopedSlots: { customRender: "remark" },
  },
  {
    title: "操作",
    dataIndex: "action",
    key: "action",
    align: "center",
    fixed: "right",
    scopedSlots: { customRender: "action" },
  },
];

export default {
  // 2. 注册
  components: {
    productPickingInfo,
    GoodsShelvesInfo,
    // footerCommonBar,
  },
  computed: {
    // 获取本地数据
    ...mapState("user", { currUser: "info", currPost: "position" }),
    ...mapGetters({
      getDepsInfo: "user/getDepsInfo",
    }),
    // ...mapState("setting", ["isMobile"]),
  },
  data() {
    return {
      isAntiAudit: false,
      // 子组件传参
      shelfWindow: false,
      goodsShelvesTag: false,
      tableKey: 0,
      storageId: "",
      position: 0,
      //货架详情
      saveShelfDetails: "",
      u8c_array: [], //u8c传递数据表格的数据源
      arr: [], //
      GeneralBillVO: [], //需给用友传递的data
      ayyany: [],
      ayyanyany: [],

      rules2: {
        responsiblePerson: [
          {
            required: true,
            trigger: "blur",
            message: "选择负责人",
          },
        ],
        inspector: [
          {
            required: true,
            trigger: "blur",
            message: "选择审核人",
          },
        ],
      },
      rules: {
        depotName: [
          {
            required: true,
            trigger: "blur",
            message: "选择仓库名称",
          },
        ],
        finishedProductDepot: [
          {
            required: true,
            trigger: "blur",
            message: "选择产成品仓库",
          },
        ],
        sendReceiveType: [
          {
            required: true,
            trigger: "blur",
            message: "选择收发类别",
          },
        ],
        pk_calbody: [
          {
            required: true,
            trigger: "blur",
            message: "选择库存组织",
          },
        ],
        ownedBranch: [
          {
            required: true,
            trigger: "change",
            message: "选择所属分厂",
          },
        ],
        finishGoodsType: [
          {
            required: true,
            trigger: "change",
            message: "选择产成品分类",
          },
        ],
      },
      precision: 3, //销售系统保留3位小数
      amountPrecision: 2, //销售系统金额保留2位小数
      // ----- 申请的表单内容信息 -----
      Form: {
        document: "", // 申请单号
        document_date: moment().format("YYYY-MM-DD"), // 单据日期 // 日期
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        finishedProductDepot: "", //产成品仓库
        finishedProductDepotId: "", //产成品仓库ID
        supplier: "", //供应商
        supplierId: "", //供应商Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        deptIdName: "", // 部门名称
        deptId: "", // 部门
        pk_corp: "山东七河生物科技股份有限公司",
        pk_corpId: "1001",
        pk_calbodyId: "1001F3100000000002LS", //库存组织ID
        pk_calbody: "山东七河生物", //库存组织名称

        storage: "", //仓库名称
        storageNo: "", // 申请仓库编码
        storageId: "", // 仓库名称ID
        ownedBranch: "", // 所属公司

        finishedProductType: "", //产成品分类名称
        finishGoodsType: "", //产成品分类
        depotName: "", //仓库名称
        depotId: "", //仓库名称
      },

      // 字典表等数据

      storageList: [], // 仓库列表，所属仓库，产成品仓库
      supplierList: [], //供应商名称
      goodsList: [], // 存货列表
      SendReceiveList: [], // 收发类别列表
      Auxiliary_Unitlist: [], // 辅助单位列表
      batchNumberList: [], // 批次号列表
      finishGoodsTypeList: [], //产成品分类列表

      customerNameList: [], //供应商列表
      farmerList: [], //农户列表

      InventoryOrganizationList: [], // 库存组织列表
      UserList: [], // 库管员列表
      workNoList: [], // 判重使用
      pk_corpList: [], // 公司列表
      ownedBranchList: [], //分厂列表

      responsiblePersonList: [], // 负责人列表
      inspectorList: [], // 审核人列表
      inspectorIdList: [], // 审核人Id列表

      updateTag: true, // 修改标志
      // ------- 表格 --------
      // 格式
      layout: {
        labelCol: { span: 8 },
        wrapperCol: { span: 15 },
      },

      // 列表
      columns,
      DataSource: [],
      recordDataSource: null, // 新增一个记录第一次值
      selectedRowKeys: [],
      randomKey: 0,
      
      Inspector: "",
    };
  },
  watch: {
    $route: function (to) {
      if (to.path == "/ProductionMaterialsOutput") {
        this.getRouterParam();
      }
    },
  },
  // 生命周期函数
  mounted() {
    this.setInitInfo(this.$route.query.Id);
    this.judgeDocument(); //判断单据号是否为空
    this.setColumns(); // 生成多条数据
    this.getApplyOrder(); // 获取申请单号
    this.getwarehouseInfo(); //获取仓库，所属仓库和产成品仓库接口
    this.getSupplierInfo(); //供应商信息列表
    this.getSendReceiveList(); //获取收发类别
    this.getFinishGoodsTypeList(); //获取产成品分类列表
    this.getSyncInventoryOrganizationList();
    this.getpk_corpList();
    this.getownedBranchTree(); //获取分厂列表
    this.getResponsiblePersonList(); // 获取负责人列表
    this.getInspectorList(); // 获取审核人
    this.getRouterParam();
    // 获取农户列表
    this.GetSupplierTreeList();
  },
  methods: {
    // ————判断单据号是否为空————
    judgeDocument() {
      setTimeout(() => {
        if (this.Form.document === "") {
          this.$message.error("未获取到单据号,请刷新页面重试");
        }
      }, 3000);
    },
    shelfDetails(record) {
      this.shelfWindow = true;
      this.saveShelfDetails = record.goodsShelves;
    },
    handleOk_shelfDetails() {
      this.shelfWindow = false;
      this.saveShelfDetails = "";
    },
    handleCancel_shelfDetails() {
      this.shelfWindow = false;
      this.saveShelfDetails = "";
    },
    // 获取货架信息
    getGoodsShelves(record) {
      this.goodsShelvesTag = true;
      this.tableKey = record.key;
      this.position = record.position;
      console.log("record", record.position);
      setTimeout(() => {
        this.$refs.goodShelvesInfo.getGoodShelveInfo();
      }, 1000);
      //
    },

    // 关闭货架
    getGoodShelveInfo(key, goodsShelvesList) {
      console.log("序号和货架列表", key, goodsShelvesList);

      let str = "";
      goodsShelvesList.forEach((element) => {
        str = str + element.inOutShelf + ",";
      });
      str = str.substring(0, str.length - 1);
      this.$set(this.DataSource[key - 1], "goodsShelves", str);

      this.closeGoodsShelves();
    },
    // 关闭货架modal
    closeGoodsShelves() {
      this.goodsShelvesTag = false;
    },
    // 获取公司
    getpk_corpList() {
      comHttp.getpk_corpList().then((res) => {
        console.log("公司", res);
        this.pk_corpList = res.result;

        this.changeCorpData(this.pk_corpList);

        console.log(123124, this.pk_corpList);
      });
    },
    // 获取公司改变用友传递过来的数据为组件能识别的数据
    changeCorpData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.unitcode + " " + element.unitname;
        element["value"] = element.unitcode + "|" + element.unitname;
        element["children"] = element.syncCompanyEntityList;
        element["key"] = element.id;

        if (element.children) {
          this.changeCorpData(element.children);
        }
      });
    },

    // 获取公司获取公司Id
    getpk_corpId(value, label, extra) {
      console.log(extra);

      let arr = this.Form.pk_corp.split("|");
      this.Form.pk_corpId = arr[0];
      this.Form.pk_corp = arr[1];
      console.log(this.Form.pk_corp, 333333333);
    },

    // 获取分厂列表
    getownedBranchTree() {
      comHttp.getDepartmentList().then((res) => {
        // let tree = this.resetTree(res.result);
        console.log("获取部门树+++++++++++::::", res);
        this.ownedBranchList = res.result;
        this.changeownedBranchData(this.ownedBranchList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeownedBranchData(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.deptname;
        element["children"] = element.syncDepartmentFilesEntityList;
        element["key"] = element.pkDeptdoc;
        element["value"] = element.pkDeptdoc;

        if (element.children) {
          this.changeownedBranchData(element.children);
        }
      });
    },
    // 部门下拉框选择
    changeTreeNode(key, value) {
      console.log("key", key);
      console.log("value", value);
      this.Form.ownedBranch = value[0];
      this.Form.ownedBranchId = key;
      console.log("选择的值::::", this.Form.ownedBranch);
      console.log("ownedBranchId::::", this.Form.ownedBranchId);
    },
    // --- 获取供应商树 ---
    GetSupplierTreeList(queryPath = "") {
      let tempdata = {
        areaclcode: "0306",
        areaclname: "农户",
        children: [],
        dr: null,
        id: 72,
        pkAreacl: "0001F31000000000048Q",
        pkCorp: "0001",
        pkFatherarea: "0001F31000000000048E",
        title: "农户",
        ts: "2021-03-18 10:18:17",
      };
      let data = {
        areaclCode: "",
        areaclName: "",
        corpName: "",
        createtime: "",
        cropCode: "",
        custcode: "",
        custflag: "1,3",
        custname: "",
        custprop: 0,
        custshortname: "",
        dr: "",
        freecustflag: "",
        freeofcremnycheck: "",
        frozenflag: "",
        id: 0,
        pkAreacl: "",
        pkCrop: "",
        pkCubasdoc: "",
        pkCumandoc: "",
        pkCurrtype1: "",
        pkSalestru: "",
        regionId: tempdata.pkAreacl,
        sealdate: "",
        ts: "",
      };
      comHttp.getSupplierInfoByArea(data, queryPath).then((res) => {
        console.log("res选中的分类下面的供应商", res);
        this.farmerList = [];
        for (let i = 0; i < res.result.records.length; i++) {
          let data = {
            No: res.result.records[i].custcode, //编号
            id: res.result.records[i].pkCumandoc,
            name: res.result.records[i].custname,
          };
          this.farmerList.push(data);
        }
        console.log("this.famerList==>", this.farmerList);
      });
    },
    // 农户列表
    // getAllfarmerList(value) {
    //   if (value != "") {
    //     comHttp
    //       .queryByLikeName("?customerName=" + value + "&custflag=0,2")
    //       .then((res) => {
    //         console.log("农户列表", res);
    //         this.farmerList = [];
    //         for (let i = 0; i < res.result.list.length; i++) {
    //           let data = {
    //             No: res.result.list[i].custcode, //编号
    //             id: res.result.list[i].pkCumandoc,
    //             name: res.result.list[i].custname,
    //           };
    //           this.farmerList.push(data);
    //         }
    //       });
    //   }
    // },
    // 获取农户列表
    getfarmerId(value) {
      console.log("value::::", value);
      let array = value.split("|");
      this.Form.farmerName = array[1];
      this.Form.farmerId = array[2];
      console.log("this.Form.farmer", this.Form.farmerId);
    },
    // 客户模糊搜索
    searchCustomer(value) {
      if (value == "") {
        this.$message.error("请输入客户名称！");
      } else if (value == " ") {
        value = "";
        console.log("value", value);
        this.$message.error("请输入真实数据！");
      } else {
        this.customerNameList = [];
        let data = "?customerName=" + value + "&custflag=3,1";
        comHttp.getCustomerInfoByName(data).then((res) => {
          console.log("res", res);
          for (let i = 0; i < res.result.list.length; i++) {
            let data = {
              id: res.result.list[i].pkCumandoc,
              customerCode: res.result.list[i].custcode,
              name: res.result.list[i].custname,
            };
            this.customerNameList.push(data);
          }
        });
      }
    },
    // 客户选择的处理函数
    changeCustomer(value) {
      console.log("客户选择处理函数", value);
      let array = value.split("|");
      this.Form.supplierCode = array[0]; //客户编码
      this.Form.supplier = array[1]; //客户名称
      this.Form.supplierId = array[2]; //客户Id
      console.log("this.form.customerId", this.Form.supplierId);
      let id = array[2]; //客户id
      console.log("id", id);
    },
    // 获取产成品分类列表
    getFinishGoodsTypeList() {
      comHttp.GetSaveCargoClassification().then((res) => {
        console.log("产成品分类列表", res);

        this.finishGoodsTypeList = res.result;
        this.changeFinishGoodsType(this.finishGoodsTypeList);
      });
    },
    // 改变用友传递过来的数据为组件能识别的数据
    changeFinishGoodsType(Tree) {
      Tree.forEach((element) => {
        element["title"] = element.invclassname;
        element["children"] = element.syncInventoryClassificationEntityList;
        element["key"] = element.invclassname;
        element["value"] = element.pkInvcl;

        if (element.children) {
          this.changeFinishGoodsType(element.children);
        }
      });
    },

    // 处理产成品分类
    setFinishGoodsType(key, value) {
      console.log("key======>", key);
      console.log("value======>", value);
      console.log("this.forafdslfdsfdsfd", this.Form.finishGoodsType);

      // console.log("value11111111111", key);
      // let array = target.finishGoodsType.split("|");
      // // console.log("array===", array);
      // target.finishGoodsTypeId = array[0];
      // target.finishGoodsType = array[1];
      // console.log("target.finishGoodsTypeId", target);
    },
    // 获取库存组织列表
    getSyncInventoryOrganizationList() {
      comHttp.getSyncInventoryOrganizationList().then((res) => {
        console.log("库存组织", res);
        this.InventoryOrganizationList = res.result;
      });
    },
    // 获取库存组织Id
    getpk_calbodyId(value, options) {
      this.Form.pk_calbodyId = options.key;
      // console.log(this.Form.pk_calbodyId, 222222222);
    },

    // 库管员列表
    getcwhsmanagerId(value, option) {
      this.Form.cwhsmanagerid = option.key;
      console.log("this.getcwhsmanagerId", this.Form.cwhsmanagerid);
    },

    // 查询人员信息列表
    searchUserInfoList(value) {
      this.UserList = [];
      this.workNoList = [];
      if (value != "") {
        let queryPath = "?username=" + value;
        comHttp.getUserInfoByUserName(queryPath).then((res) => {
          for (let i = 0; i < res.result.list.length; i++) {
            if (!this.workNoList.includes(res.result.list[i].workNo)) {
              let data = {
                userName: res.result.list[i].username,
                userId: res.result.list[i].id,
                workNo: res.result.list[i].workNo,
              };
              this.UserList.push(data);
              this.workNoList.push(res.result.list[i].workNo);
            }
          }
        });
      }
    },

    // 领料员列表处理函数
    getPickerId(value, option) {
      this.Form.pickerId = option.key;
      this.Form.picker = value;
    },
    changecwhsmanager(value, option) {
      this.Form.cwhsmanagerid = option.key;
      this.Form.cwhsmanager = value;
    },
    // !存货信息模糊查询
    //延迟
    debounce(value, wait) {
      if (this.timeout) clearTimeout(this.timeout);
      this.timeout = setTimeout(() => {
        this.onfunc(value);
      }, wait);
    },
    handleInventoryInfoSearch(value) {
      this.debounce(value, 30);
    },
    // !下拉框搜索
    async onfunc(value) {
      var goodsList_invname = [];
      var goodsList_invspec = [];
      console.log("value!!!!!", value);
      if (value.match(/^[ ]*$/)) {
        console.log("字符串为空或全空格");
      } else {
        this.goodsList = [];
        console.log("value", value);
        let queryPath = "?name=" + value;
        console.log("query", queryPath);
        if (value == "" || value == null) {
          this.goodsList = [];
        } else {
          await comHttp
            .getSearchInventoryInformationFile(queryPath)
            .then((res) => {
              console.log("res", res.result);
              for (let i = 0; i < res.result.length; i++) {
                let data = {
                  inventoryId: res.result[i].pkInvbasdoc, // 存货 id
                  inventoryName: res.result[i].invname,
                  inventoryNo: res.result[i].invcode,
                  standardModel: res.result[i].invspec,
                  unit: res.result[i].measname,
                };
                goodsList_invname.push(data);
              }
              console.log("this.goodsList====>", this.goodsList);
            });

          let queryInventoryBySpec = "?invspec=" + value;
          //规格型号模糊查询
          await comHttp
            .getqueryInventoryBySpec(queryInventoryBySpec)
            .then((res) => {
              console.log("结果规格型号模糊查询", res);

              goodsList_invspec = res.result.list.map((item) => {
                return {
                  inventoryId: item.pkInvbasdoc,
                  inventoryNo: item.invcode,
                  inventoryName: item.invname,
                  standardModel: item.invspec,
                  unit: item.measname,
                };
              });
            });
          //todo 合并去重函数
          await this.mergeArray(goodsList_invname, goodsList_invspec);
        }
      }
    },
    //todo 合并去重函数
    mergeArray(arr1, arr2) {
      let arrs = [...arr1, ...arr2];

      //根据inventoryId去重
      let map = new Map();
      for (let item of arrs) {
        if (!map.has(item.inventoryId)) {
          map.set(item.inventoryId, item);
        }
      }
      this.goodsList = [...map.values()];
    },
    // 获取路由参数
    getRouterParam() {
      console.log("查询参数:::", this.$route.query.Id);
      // 通过出入库id 查询出入库信息
      if (typeof this.$route.query.Id == "undefined") {
        console.log("常规跳转");
      } else {
        this.isAntiAudit = true;
        this.Inspector = this.$route.query.Inspector;

        console.log("this.Inspector=====》", this.Inspector);
        this.setInitInfo(this.$route.query.Id);
      }
    },
    // 初始化数据
    InitOriginData() {
      this.Form = {
        document: "", // 申请单号
        document_date: moment().format("YYYY-MM-DD"), // 单据日期 // 日期
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        finishedProductDepot: "", //产成品仓库
        finishedProductDepotId: "", //产成品仓库ID
        supplier: "", //供应商
        supplierId: "", //供应商Id
        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
        deptIdName: "", // 部门名称
        deptId: "", // 部门
        pk_corp: "山东七河生物科技股份有限公司",
        pk_corpId: "1001",
        pk_calbodyId: "1001F3100000000002LS", //库存组织ID
        pk_calbody: "山东七河生物", //库存组织名称

        storage: "", //仓库名称
        storageNo: "", // 申请仓库编码
        storageId: "", // 仓库名称ID
        ownedBranch: "", // 所属公司

        finishedProductType: "", //产成品分类名称
        finishGoodsType: "", //产成品分类
        depotName: "", //仓库名称
        depotId: "", //仓库名称
      };
      // 初始化表单数据
      this.DataSource = [];
      this.updateTag = true;
      // 初始化表格数据
      // this.InitDataSource();
    },
    // 通过路由跳转，设置初始化信息
    async setInitInfo(id) {
      if (this.$route.query.isAntiAudit == "已反审核") {
        this.isAntiAudit = true;
      }
      if (typeof id === "undefined") {
        this.InitOriginData();
        // this.getApplyOrder();
      } else {
        comHttp
          .getInOrOutStorageOrderAndGoodsInfoById("?id=" + id)
          .then((res) => {
            this.DataSource = [];

            console.log("通过Id查询出来的信息::::", res);
            if (this.$route.query.isAntiAudit == "已反审核") {
              this.isAntiAudit = true;
            }
            this.otherId = res.result.list[0].otherId; // 表一 Id
            this.Form = {
              id: res.result.list[0].otherId, // 表一 Id
              document: res.result.list[0].document, // 单据号
              document_date: res.result.list[0].documentDate, // 单据日期
              deptIdName: res.result.list[0].deptId_dictText, // 申请部门
              department: res.result.list[0].deptId_dictText, // 部门
              // 供应商
              supplier: res.result.list[0].supplier_dictText,
              supplierId: res.result.list[0].supplier,
              // 仓库名称
              depotId: res.result.list[0].pkStordoc,
              depotName: res.result.list[0].storname,
              // 产成品分类
              finishGoodsType: res.result.list[0].finishedProductType,
              // finishGoodsType: res.result.list[0].finishedProductType,
              // 产成品仓库
              finishedProductDepot:
                res.result.list[0].finishedProductDepot_dictText,
              finishedProductDepotId: res.result.list[0].finishedProductDepot,

              sendReceiveType: res.result.list[0].sendReceiveType_dictText, // 收发类别
              sendReceiveTypeId: res.result.list[0].sendReceiveType, // 收发类别Id

              responsiblePerson: res.result.list[0].responsiblePerson_dictText, // 负责人
              responsiblePersonId: res.result.list[0].responsiblePerson,
              inspector: res.result.list[0].inspector_dictText, // 审核人
              inspectorId: res.result.list[0].inspector,
              singleProducer: res.result.list[0].singleProducer_dictText, // 制单人
              singleProducerId: res.result.list[0].singleProducer,
              balance: res.result.list[0].balance,
              pk_corp: res.result.list[0].pkCorp_dictText, //所属公司
              pk_corpId: res.result.list[0].pkCorp, //所属公司ID
              pickerId: res.result.list[0].picker, //领料员ID
              picker: res.result.list[0].picker_dictText, //领料员
              cwhsmanagerid: res.result.list[0].cwhsmanagerid, //库管员ID
              cwhsmanager: res.result.list[0].cwhsmanagerid_dictText, //库管员
              pk_calbodyId: res.result.list[0].pkCalbody, //库存组织Id
              pk_calbody: res.result.list[0].pkCalbody_dictText, //库存组织
              farmerId: res.result.list[0].farmer, //农户ID
              farmer: res.result.list[0].farmer_dictText, //农户
              ownedBranchId: res.result.list[0].ownedBranch, //所属分厂
              ownedBranch: res.result.list[0].ownedBranch_dictText, //所属分厂
            };

            for (let i = 0; i < res.result.list.length; i++) {
              // 获取仓位列表 异步加载
              let positionList = this.getPositionList(
                res.result.list[i].depotId
              );
              console.log("log positionList==>", positionList);
              if (positionList != 1) {
                // console.log("獲取的數據:::", res);
                let temp_data = this.disableParent(res);
                // console.log("獲取的數據:::", temp_data);
                positionList = temp_data;
              }
              if (res.result.list[i].batchNumber == "null") {
                res.result.list[i].batchNumber = "";
              }
              let data = {
                key: i + 1,
                id: res.result.list[i].twoId, // 表二 Id
                otherId: res.result.list[i].otherId, // 表一Id
                isNew: false,

                depotId: res.result.list[i].depotId, // 仓库Id
                depotNo: res.result.list[i].storcode, // 仓库编码
                depotName: res.result.list[i].storname, // 仓库名称

                depotLocation: res.result.list[i].depotLocation, // 库位
                position: res.result.list[i].position, // 仓位

                inventoryId: res.result.list[i].inventoryId, // 存货Id
                inventoryNo: res.result.list[i].invcode, // 存货编码
                inventoryName: res.result.list[i].invname, // 存货名称
                standardModel: res.result.list[i].invspec, // 规格型号
                unit: res.result.list[i].measname, // 单位
                quantity: res.result.list[i].quantity, // 数量
                sourceNumber: res.result.list[i].sourceNumber, // 源单单号
                batchNumber: res.result.list[i].batchNumber, // 批次号
                finishedProductType: res.result.list[i].finishedProductType, // 产成品分类Id
                finishedProductTypeId: res.result.list[i].finishedProductType, // 产成品分类
                amountOfFruitPicking: res.result.list[i].amountOfFruitPicking, // 出菇领料金额

                deliveryDate: res.result.list[i].deliveryDate, // 出库日期
                remark: res.result.list[i].remark, // 备注
              };

              // data[`goodsList`] = this.getGoodSInfo(res.result.list[i].depotId);
              // 批次号列表 异步加载
              this.getBatchNumberList(
                res.result.list[i].depotId,
                res.result.list[i].inventoryId,
                res.result.list[i].position
              ).then(async (res) => {
                this.$set(data, "BatchList", res);
              });

              this.DataSource.push(data);
            }
            this.updateTag = false;
            this.sortArr(res.result.list, "depotNo");
          });
      }
    },

    // 获取所属仓库,表格触发事件
    getstorageUnitId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.storageUnit.split("|");
      target.storageUnitNo = array[0]; // 仓库id
      target.storageUnit = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.storageUnitId = SotrageInfo.depotId;
      console.log("表格所属仓库::::", target.storageUnitId);
    },
    // 默认设置五行，让用户方便添加
    setColumns() {
      let size = 1;
      this.DataSource = [];
      for (let i = 0; i < size; i++) {
        let data = {
          key: i + 1,
          isNew: true,
          depotId: "", // 仓库Id
          depotNo: "", // 仓库编码
          depotName: "", // 仓库名称
          depotLocation: "", // 库位
          position: "", // 仓位

          storageUnit: "", // 所属仓库名称
          storageUnitId: "", // 所属仓库Id

          inventoryId: "", // 存货Id
          inventoryNo: "", // 存货编码
          inventoryName: "", //  存货名称
          standardModel: "", // , 规格型号
          unit: "", // 单位
          existingQuantity: 0, //现存数量
          quantity: "", // 	数量
          unitPrice: "", // 单价
          money: "", // 金额
          amountOfFruitPicking: "", // 金额

          batchNumber: null, // 批次号
          finishedProductType: "", //产成品分类
          finishedProductTypeId: "", // 产成品分类Id

          sourceNumber: "", // 源单单号（外键）
          deliveryDate: this.Form.document_date, // 出库日期
          remark: "", // 备注

          goodsList: [], // 物品信息列
          BatchList: [], // 批次列表
          positionList: [], // 仓位列表
        };
        this.DataSource.push(data);
      }
      // console.log("默认加载的数据::::",this.DataSource)
    },

    // 所属仓库，仓库名称，产成品仓库
    getwarehouseInfo() {
      comHttp.getStorageName().then((res) => {
        console.log("仓库名称列表", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            depotId: res.result[i].pkStordoc,
          };
          this.storageList.push(data);
        }
      });
    },

    // 处理产成品仓库函数
    setFinishProduct(value, option) {
      let array = value.split("|");
      this.Form.finishedProductDepot = array[1];
      this.Form.finishedProductDepotId = option.key;
      console.log("产成品仓库Id::::", this.Form.finishedProductDepotId);
    },

    // 获取收发类别列表
    getSendReceiveList(queryPath = "") {
      // console.log("State:::::",  this.$store.state);

      comHttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表:::::", res);
        console.log("收发类别列表", res);
        this.SendReceiveList = res.result.filter(
          (item) => item.receiveFlag === 1
        );
      });
    },
    // 获取收发类别Id
    getSendReceiveTypeId(value) {
      console.log("收发类别触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      console.log("array[0]", array[0]);
      console.log("array[1]", array[1]);
      // 表格自动填充所属单位
      this.Form.sendReceiveTypeId = array[0]; //收发类别id
      this.Form.sendReceiveType = array[1]; //收发类别name
    },

    // 仓库名称选择函数,后同时修改下方表格中的仓库名称和仓库编码
    changeStorageInfo(value, option) {
      let array = value.split("|");
      this.Form.storageNo = array[0];
      this.Form.storage = array[1];
      this.Form.storageId = option.key;
      console.log(" this.Form.storageId", this.Form.storageId);
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].warehouseNumber = array[0];
        this.DataSource[i].warehouse = array[1];
      }
    },

    // 获取物品信息,后期可能会修改为根据仓库id获取物品信息，因为物品信息是根据仓库id来的！！！！！
    // getGoodSInfo(id) {
    //   let goodsList = [];
    //   comHttp.getInventoryInformationByStorageId("?id=" + id).then((res) => {
    //     // console.log("获取存货信息:::::", res);
    //     for (let i = 0; i < res.result.length; i++) {
    //       let data = {
    //         inventoryId: res.result[i].id, // 存货 id
    //         inventoryName: res.result[i].inventoryName,
    //         inventoryNo: res.result[i].inventoryNo,
    //         standardModel: res.result[i].specificationsModel,
    //         unit: res.result[i].unit,
    //       };
    //       goodsList.push(data);
    //     }
    //     console.log(goodsList);
    //   });
    //   return goodsList;
    // },

    //存货编码处理函数
    changeHandleInventory(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log(target);
      // 分割字符串,取出来存货编码
      let array = target.inventory_no.split("|");
      // console.log("存货编码为:::", array[0]);
      target.inventory_no = array[0]; // 赋值给存货编码
      target.inventory_name = array[1]; // 赋值给存货名称
      target.standard_model = array[2]; // 赋值给规格型号
      target.unit = array[3]; // 赋值给单位

      // 根据存货编码获取存货信息::::
    },

    // 获取全部的仓位信息
    getPositionInformationList() {
      comHttp.getPositionInformationList().then((res) => {
        console.log("仓位信息:::::", res);
      });
    },

    // 获取产成品分类
    getFinishGoodsType() {
      comHttp.GetSaveCargoClassification().then((res) => {
        console.log("产成品分类列表", res);

        this.finishGoodsTypeList = res.result;
      });
    },

    // 格式化出库日期
    formatDeliveryDate(key) {
      this.randomKey = Math.random();
      let target = this.DataSource.filter((item) => item.key === key)[0];
      target.deliveryDate = moment(target.deliveryDate).format("YYYY-MM-DD");
      console.log("修改好的时间为::::", target.deliveryDate);
    },

    // 获取存货信息
    async getInventoryInfo(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log("target===============>", target);
      // 分割字符串,取出来存货编码
      let array = target.inventoryName.split("|");
      target.inventoryNo = array[0]; // 赋值给存货编码
      target.inventoryName = array[1]; // 赋值给存货名称
      // target.standardModel = array[2]; // 赋值给存货名称
      // target.unit = array[3]; // 赋值给存货名称
      // console.log("目标物品信息:::::",target.goodsList)

      // 递归查询出来物品信息
      let goodsInfomation = [];
      for (let i = 0; i < this.goodsList.length; i++) {
        if (this.goodsList[i].inventoryNo == array[0]) {
          goodsInfomation = this.goodsList[i];
        }
      }
      console.log("goodsInfomation===>", goodsInfomation);
      target.standardModel = goodsInfomation.standardModel;
      target.unit = goodsInfomation.unit;

      target.inventoryId = goodsInfomation.inventoryId;
      console.log("存货编码::::", target.inventoryId);

      // 批次列表
      target.BatchList = await this.getBatchNumberList(
        target.depotId,
        goodsInfomation.inventoryId,
        target.position
      );
      console.log("批次号列表::::", target.BatchList);
      // if (target.position == "null" || target.position == undefined) {
      //   target.position == "";
      // } else if (
      //   target.sourceNumber == "null" ||
      //   target.sourceNumber == undefined
      // ) {
      //   target.sourceNumber == "";
      // } else if (
      //   target.batchNumber == "null" ||
      //   target.batchNumber == undefined
      // ) {
      //   target.batchNumber == "";
      // } else {
      //   let tempData = {
      //     batchNumber: target.batchNumber,
      //     depotId: parseInt(target.depotId), //仓库Id
      //     inventoryId: parseInt(target.inventoryId), //存货名称
      //     position: parseInt(target.position), //仓位
      //     sourceNumber: target.sourceNumber,
      //   };
      // }
    },
    // 批次号处理列表
    getBatchNumberInfo(key) {
      console.log("111111111111111");
      let tempData = {};
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log("target", target);
      if (target.position == "null" || target.position == undefined) {
        target.position == "";
      } else if (
        target.sourceNumber == "null" ||
        target.sourceNumber == undefined
      ) {
        target.sourceNumber == "";
      } else if (
        target.batchNumber == "null" ||
        target.batchNumber == undefined
      ) {
        target.batchNumber == "";
      } else {
        tempData = {
          batchNumber: target.batchNumber,
          depotId: parseInt(target.depotId), //仓库Id
          inventoryId: parseInt(target.inventoryId), //存货名称
          position: parseInt(target.position), //仓位
          sourceNumber: target.sourceNumber,
        };
      }
      comHttp.getExistingQuantity(tempData).then((res) => {
        target.existingQuantity = res.result.balance;
      });
      console.log("this.getExistingQuantity", target.existingQuantity);
    },
    // !获取现存数量
    getExistingQuantity(data) {
      let temp = "";
      // return new Promise((resolve) => {
      comHttp.getExistingQuantity(data).then((res) => {
        temp = res.result.balance;
        console.log("temp", temp);
        console.log("res=================>", res);
        return temp;
        // resolve(temp);
        // });
      });
    },
    // 申请日期
    onChange(date, dateString) {
      console.log(date, dateString);
    },

    // 表格添加新的一条记录
    newMember() {
      // 保存第一次的状态
      if (!this.recordDataSource) {
        this.recordDataSource = this.DataSource;
      }

      // let data1 = data.goodsList;
      const copyData = this.recordDataSource.map((item, index) => {
        return {
          ...item,
          key: this.DataSource.length + index + 1,
          isNew: true,
          quantity: 0, // 	出库数量
          amountOfFruitPicking: "", //出谷领料金额
          batchNumber: "", // 批次号
          existingQuantity: 0,
          remark: "", //备注
          BatchList: [], // 批次列表
          goodsShelves: "", // 货架
        };
      });
      this.DataSource = [...this.DataSource, ...copyData];
      // for (let i = 0; i < this.form.goodsList.length; i++) {
      //   let data = {
      //     key: this.DataSource.length + 1,
      //     isNew: true,

      //     depotId: this.form.goodsList[i].depotId, // 仓库Id
      //     depotNo: this.form.goodsList[i].depotIdBac_dictText, // 仓库编码
      //     depotName: this.form.goodsList[i].depotId_dictText, // 仓库名称
      //     // depotLocation: "", // 库位
      //     position: "", // 仓位

      //     // storageUnit: "", // 所属仓库名称
      //     // storageUnitId: "", // 所属仓库Id

      //     inventoryId: this.form.goodsList[i].inventoryId, // 存货Id
      //     inventoryNo: this.form.goodsList[i].inventoryNo, // 存货编码
      //     inventoryName: this.form.goodsList[i].invname, //  存货名称
      //     standardModel: this.form.goodsList[i].invspec, // , 规格型号
      //     unit: this.form.goodsList[i].measname, // 单位

      //     quantity: 0, // 	数量
      //     unitPrice: "", // 单价
      //     money: "", // 金额

      //     batchNumber: "", // 批次号

      //     sourceNumber: this.form.goodsList[i].requisitionNo, // 源单单号（外键）
      //     deliveryDate: this.Form.document_date, // 出库日期
      //     remark: "", // 备注

      //     goodsList: [], // 物品信息列
      //     BatchList: [], // 批次列表
      //     positionList: [], // 仓位列表
      //     goodsShelves: "", // 货架
      //   };
      //   this.DataSource.push(data);
      // }
      // this.DataSource.push({
      //   key: this.DataSource.length + 1,
      //   isNew: true,
      //   depotId: "", // 仓库Id
      //   depotNo: "", // 仓库编码
      //   depotName: "", // 仓库名称
      //   depotLocation: "", // 库位
      //   position: "", // 仓位
      //   storageUnit: "", // 所属仓库名称
      //   storageUnitId: "", // 所属仓库Id
      //   inventoryId: "", // 存货Id
      //   inventoryNo: "", // 存货编码
      //   inventoryName: "", //  存货名称
      //   standardModel: "", // , 规格型号
      //   unit: "", // 单位
      //   quantity: "", // 	数量
      //   unitPrice: "", // 单价
      //   money: "", // 金额
      //   batchNumber: "", // 批次号
      //   finishedProductType: "", //产成品分类
      //   finishedProductTypeId: "", // 产成品分类Id
      //   sourceNumber: "", // 源单单号（外键）
      //   deliveryDate: this.Form.document_date, // 出库日期
      //   remark: "", // 备注
      //   goodsList: [], // 物品信息列
      //   BatchList: [], // 批次列表
      //   positionList: [], // 仓位列表
      //   goodsShelves: "", // 货架
      // });
    },

    // 表格取消一行
    cancle(key) {
      // console.log(key);
      if (this.DataSource.length > 1) {
        this.DataSource.splice(key - 1, 1);
        // 对序号进行重新赋值
        for (let i = key - 1; i < this.DataSource.length; i++) {
          this.DataSource[i].key = i + 1;
        }

        this.$message.success("取消成功");
      } else {
        this.$message.error("至少保留一行");
      }
    },

    // 表格选择事件,
    onSelectChange(selectedRowKeys) {
      console.log("selectedRowKeys changed: ", selectedRowKeys);
      this.selectedRowKeys = selectedRowKeys;
    },

    // 更新表单和物品数据
    updateOrderAndGoodsData() {
      console.log(this.Form);
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let updateArray = [];
      console.log("数据：：：：：", newData);
      // 物品
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].isNew == false) {
          let data = {
            id: newData[i].id, // 表二Id
            storageUnit: newData[i].storageUnitId, // 所属仓库
            depotId: newData[i].depotId, // 仓库编码
            depotLocation: newData[i].depotLocation, // 库位
            position: newData[i].position, // 仓位
            inventoryId: newData[i].inventoryId, // 存货编码
            quantity: newData[i].quantity, // 数量
            // 单价
            // 金额
            sourceNumber: newData[i].sourceNumber, // 源单单号
            batchNumber: newData[i].batchNumber, // 批次号
            // finishedProductType: newData[i].finishedProductTypeId, // 产成品分类
            deliveryDate: newData[i].deliveryDate, // 出库日期
            remark: newData[i].remark, // 备注
            amountOfFruitPicking: newData[i].amountOfFruitPicking, // 出菇领料金额
          };
          updateArray.push(data);
        }
      }
      // 单据
      let data = {
        id: this.Form.id,
        document: this.Form.document, // 单据号
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"), // 单据日期
        supplier: this.Form.supplierId, // 供应商
        finishedProductDepot: this.Form.finishedProductDepotId, // 产成品仓库
        sendReceiveType: this.Form.sendReceiveTypeId, // 收发类型Id
        deptId: this.Form.deptId, //部门id
        responsiblePerson: this.Form.responsiblePersonId, // 负责人Id
        inspector: this.Form.inspectorId, // 审核人(传userid)
        warehouseObjectInformationEntities: updateArray,

        pkCorp: this.Form.pk_corpId, //公司Id
        cwhsmanagerid: this.Form.cwhsmanagerid, //库管员
        pkCalbody: this.Form.pk_calbodyId, //库存组织
        farmer: this.Form.farmerId, //农户
        ownedBranch: this.Form.ownedBranchId, //所属分厂
        picker: this.Form.pickerId, //所属分厂
        finishedProductType: this.Form.finishGoodsType, //产成品分类
      };

      console.log("要更新的数据::::::", data);
      comHttp.updateInOrOutStorageOrderAndGoods(data).then((res) => {
        if (res.code == 200) {
          this.$message.success("修改成功");
          this.save_u8c();
          this.$router.push("/ProductionMaterialsOutputList");
          // this.Reset();
        } else {
          this.$message.error("修改失败");
        }
      });
    },

    // 新增物品数据
    addGoodsData() {
      let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let addArray = [];
      for (let i = 0; i < newData.length; i++) {
        if (newData[i].isNew == true) {
          let data = {
            otherId: this.otherId, // 表一Id
            storageUnit: newData[i].storageUnitId, // 所属仓库
            depotId: newData[i].depotId, // 仓库编码
            depotLocation: newData[i].depotLocation, // 库位
            position: newData[i].position, // 仓位
            inventoryId: newData[i].inventoryId, // 存货编码
            quantity: newData[i].quantity, // 数量
            // 单价
            // 金额
            sourceNumber: newData[i].sourceNumber, // 源单单号
            batchNumber: newData[i].batchNumber, // 批次号
            finishedProductType: newData[i].finishedProductTypeId, // 产成品分类
            deliveryDate: newData[i].deliveryDate, // 出库日期
            remark: newData[i].remark, // 备注
            amountOfFruitPicking: newData[i].amountOfFruitPicking, // 出菇领料金额
          };
          addArray.push(data);
        }
      }
      // 新增接口
      comHttp.addInOrOutStorageGoods(addArray).then((res) => {
        console.log(res);
      });
    },
    // this.u8c_array数组根据仓库编码筛选，将相同的仓库编码放在一个数组里
    sortArr(arr, str) {
      var newArr = [],
        newArrItem = [],
        // 临时变量
        tempArr = [];
      // 按照特定的参数将数组排序将具有相同值的排在一起
      arr = arr.sort(function (a, b) {
        var s = a[str],
          t = b[str];

        return s < t ? -1 : 1;
      });

      if (arr.length) {
        tempArr = arr[0][str];
      }

      // 将相同类别的对象添加到统一个数组
      for (var i in arr) {
        if (arr[i][str] === tempArr) {
          console.log("tempArr", tempArr);
          newArrItem.push(arr[i]);
        } else {
          tempArr = arr[i][str];
          newArr.push(newArrItem);
          newArrItem = [arr[i]];
        }
      }
      // 将最后的内容推出新数组
      newArr.push(newArrItem);
      this.u8c_array = newArr;
      console.log("u8c_arr", this.u8c_array);
    },
    // 点击提交按钮，将产成品入库单传递给用友
    save_u8c() {
      for (let i = 0; i < this.u8c_array.length; i++) {
        console.log("i", i);

        this.arr = [];
        for (let j = 0; j < this.u8c_array[i].length; j++) {
          console.log("j", j);
          console.log("this.u8c_array[i].length", this.u8c_array[i].length);
          let data = {
            cinventoryid: this.u8c_array[i][j].invcode, //存货ID √
            noutnum: this.u8c_array[i][j].quantity, //实出数量 √
            vsourcebillcode: this.u8c_array[i][j].document, //单据号 √
            vnotebody: this.u8c_array[i][j].remark, // 行备注 √
            dbizdate: moment(this.u8c_array[i][j].deliveryDate).format(
              "YYYY-MM-DD"
            ), //出库日期（业务日期）√
            pk_defdoc4: this.u8c_array[i][j].amountOfFruitPicking, //出菇领料金额
          };
          this.arr.push(data);
          console.log("this.arr", this.arr);
        }
        this.ayyany = {
          parentvo: {
            cdispatcherid: this.u8c_array[i][0].sendReceiveType1_dictText, //收发类别名称 √
            coperatorid: this.u8c_array[i][0].singleProducerByCode_dictText, //制单人  √
            cbizid: this.u8c_array[i][0].workNO, //业务员ID（领料员） √
            cwhsmanagerid: this.u8c_array[i][0].cwhsmanagerid1_dictText, //库管员ID  √
            cdptid: this.u8c_array[i][0].cdptidByCode_dictText, //部门 √
            cwarehouseid: this.u8c_array[i][0].storcode, //仓库id  √
            dbilldate: moment(this.u8c_array[i][0].documentDate).format(
              "YYYY-MM-DD"
            ), //单据日期
            pk_calbody: "100001", //库存组织PK=仓库编号
            pk_corp: "1001", //公司
            vreceiptcode: this.u8c_array[i][0].document, //单据号 √
            vbillcode: this.u8c_array[i][0].document, //!单据号 √
            vuserdef5: this.u8c_array[i][0].finishedProductType1_dictText, // 自定义项5-产成品分类 √
            vuserdef6: this.u8c_array[i][0].finishedProductDepot1_dictText, // 自定义项6-产成品仓库 √
            vuserdef3: this.u8c_array[i][0].farmer1_dictText, //自定义项3-农户 √
            vnote: "", //备注 √
          },
          childrenvo: this.arr,
        };

        this.ayyanyany.push(this.ayyany);
      }
      console.log("this.GeneralBillVO::::", this.ayyanyany);
      // u8c接口
      axios({
        headers: {
          "Access-Control-Allow-Origin": "*",
          trantype: "code",
          "Content-Type": "application/json",
          usercode: "13355262265",
          password: "5ef208ee90e5504a7b569ebbd6342634",
          system: "test",
        },
        method: "post",
        url: "/api/u8cloud/api/ic/materialout/save/sign",
        data: {
          GeneralBillVO: this.ayyanyany,
        },
      }).then((response) => {
        console.log("response====>", response);
        console.log(response.data.status, 666666666666666666);
        let _data = JSON.parse(response.data.data);
        console.log(_data, 7777777777777);

        if (response.data.status === "success") {
          this.$message.success("同步成功");
          this.updateSucessRecordTag = true;
          this.Form.isSynchronized = "已同步";
          this.postSynchronized("已同步");
          this.Form.vbillcode = _data[0].parentvo.vbillcode;
          console.log("this.Form.vbillcode", this.Form.vbillcode);
          this.savecoperator = _data[0].parentvo.coperatorid_code;
          console.log("this.Form.savecoperator", this.savecoperator);
          // 跳转回列表页面
          // this.$router.push("/ProductionMaterialsOutputList");
          // alert("同步成功！");
        } else {
          // this.$message.success("同步失败");
          this.$message.error(response.data.errormsg);
        }
      });
    },
    //是否同步标志位
    postSynchronized(isSynchronized) {
      let data = {
        id: this.Form.id,
        isSynchronized: isSynchronized,
      };
      console.log(data, "11111111111");
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res, 11111111111111111111);
      });
    },
    //是否反审核标志位
    update_audit(isAntiAudit) {
      let data = {
        id: this.Form.id,
        isAntiAudit: isAntiAudit,
      };
      console.log(data, "2222222222222");
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res, 2222222222222);
      });
    },
    //审核标志位
    update_Mark(isOrNo) {
      let data = {
        id: this.Form.id,
        auditMark: isOrNo,
        balance: "",
      };
      this.Form.balance = "";
      console.log(data, "33333333333333333");
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        console.log(res, 33333333333333);
      });
    },
    // 获取负责人列表
    getResponsiblePersonList() {
      const roleName = "仓库负责人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.responsiblePersonList.push(data);
        }
      });
    },
    // 设置负责人id
    setResponsible_person(value, options) {
      let array = value.split("|");
      this.Form.responsiblePerson = array[1];
      this.Form.responsiblePersonId = options.key;
    },
    // 获取审核人
    getInspectorList() {
      const roleName = "仓库审核人员";
      let queryPath = "?roleName=" + roleName;
      comHttp.getUserRoleNameByUserNameId(queryPath).then((res) => {
        // console.log(res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            userName: res.result[i].userName,
            userId: res.result[i].userId,
            workNo: res.result[i].workNo,
          };
          this.inspectorList.push(data);
          this.inspectorIdList.push(res.result[i].userId);
        }
        if (this.inspectorIdList.indexOf(this.$store.state.user.info.id) > -1) {
          // 按钮状态改变:::::
          console.log(this.ExamineDisplay);
          this.ExamineDisplay = false;
        } else {
          this.ExamineDisplay = true;
        }
      });
    },
    // 设置审核人id
    setInspector(value, options) {
      let array = value.split("|");
      this.Form.inspector = array[1];
      this.Form.inspectorId = options.key;
    },

    // 重置
    Reset() {
      // 重置表单
      this.Form = {
        pk_corp: "山东七河生物科技股份有限公司",
        pk_corpId: "1001",
        pk_calbodyId: "1001F3100000000002LS", //库存组织ID
        pk_calbody: "山东七河生物", //库存组织名称

        document: "", // 申请单号
        document_date: moment().format("YYYY-MM-DD"), // 单据日期 // 日期, // 单据日期
        sendReceiveType: "", // 收发类别名称
        sendReceiveTypeId: "", // 收发类别Id
        finishedProductDepot: "", //产成品仓库
        finishProductInventoryNo: "", //产成品仓库编码
        finishedProductDepotId: "", //产成品仓库ID
        supplier: "", //供应商
        supplierId: "", //供应商Id
        deptId: "", // 部门id
        finishGoodsType: "", //产成品分类
        finishedProductType: "", //产成品分类Id

        responsiblePerson: "", // 负责人名称
        responsiblePersonId: "", // 负责人Id
        inspector: "", // 审核人名称
        inspectorId: "", // 审核人Id
        balance: moment().format("YYYY-MM-DD"), // 审核日期
        singleProducer: this.$store.state.user.info.username, // 制单人名称
        singleProducerId: this.$store.state.user.info.id, // 制单人Id
      };
      // 重置表格
      this.DataSource = [];
      // 重新加载单据号
      this.getApplyOrder();
      // 重新设置表格列
      this.setColumns();
    },

    // --------------------

    // 保存
    Save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$refs.ruleForm2.validate((valid2) => {
            if (valid2) {
              // 通过更新标志来控制，是否是路由跳转过来的，还是新打开的页面
              // 如果是路由跳转过来的，那就是在原有的基础上进行修改，走修改接口和新增接口，修改物品和新增订单物品
              // 如果不是路由跳转过来的，走新增两个接口，新增订单和新增订单物品
              if (this.updateTag) {
                // 新增数据,新增表单数据和物品数据
                this.addOrderDataAndGoodsData();
              } else {
                this.updateOrderAndGoodsData(); // 更新表单和物品数据
                this.addGoodsData(); // 新增物品数据
              }
            }
          });
        }
      });
    },
    // 审核+修改
    Check() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.$refs.ruleForm2.validate((valid2) => {
            if (valid2) {
              // 通过更新标志来控制，是否是路由跳转过来的，还是新打开的页面
              // 如果是路由跳转过来的，那就是在原有的基础上进行修改，走修改接口和新增接口，修改物品和新增订单物品
              // 如果不是路由跳转过来的，走新增两个接口，新增订单和新增订单物品
              this.Examine();
              this.updateOrderAndGoodsData(); // 更新表单和物品数据
              this.addGoodsData(); // 新增物品数据
            }
          });
        }
      });
    },
    // 审核函数
    Examine() {
      // this.Form.balance = moment().format("YYYY-MM-DD");
      console.log(this.Form.balance);
      let data = {
        id: this.Form.id,
        auditMark: 1,
        isAntiAudit: "未反审核",
        balance: this.Form.balance,
      };

      // 提交审核信息，修改表一数据
      comHttp.updateInOrOutStorageOrder(data).then((res) => {
        if (res.code == 200) {
          console.log("审核成功");
          // this.$message.success("审核成功");
        } else {
          console.log("审核失败");
          // this.$message.success("审核失败");
        }
      });
    },

    // 新增数据,新增表单数据和物品数据
    addOrderDataAndGoodsData() {
      // 过滤物品编码
      // let newData = this.DataSource.filter((item) => item.inventoryNo != "");
      let newData = this.DataSource;
      console.log(this.DataSource, "999999999999999999");
      let array = [];

      for (let i = 0; i < newData.length; i++) {
        if (
          newData[i].depotId == "undefined" ||
          newData[i].depotId == "null" ||
          newData[i].depotId == ""
        ) {
          this.$message.error("请选择仓库单位！");
        } else if (
          newData[i].inventoryId == "undefined" ||
          newData[i].inventoryId == "null" ||
          newData[i].inventoryId == ""
        ) {
          this.$message.error("请选择存货编码 ！");
        } else if (
          newData[i].quantity == "undefined" ||
          newData[i].quantity == "null" ||
          newData[i].quantity == ""
        ) {
          this.$message.error("请填写存货数量 ！");
        } else if (newData[i].batchNumber == "undefined") {
          this.$message.error("请选择批次号 ！");
        } else if (
          newData[i].deliveryDate == "undefined" ||
          newData[i].deliveryDate == "null" ||
          newData[i].deliveryDate == ""
        ) {
          this.$message.error("请填写出库日期 ！");
        } else {
          let data = {
            depotId: newData[i].depotId, // 仓库编码
            // depotLocation: newData[i].depotLocation, // 库位
            position: newData[i].position, // 仓位
            inventoryId: newData[i].inventoryId, // 存货编码
            quantity: newData[i].quantity, // 数量
            // 单价
            // 金额
            sourceNumber: newData[i].sourceNumber, // 源单单号
            batchNumber: newData[i].batchNumber, // 批次号
            finishedProductType: newData[i].finishedProductType, // 产成品分类
            deliveryDate: newData[i].deliveryDate, // 出库日期
            remark: newData[i].remark, // 备注
            amountOfFruitPicking: newData[i].amountOfFruitPicking, // 出菇领料金额
            pickingContentId: newData[i].pickingContentId,
            remarkShelf: newData[i].goodsShelves, //货架号
          };
          array.push(data);
        }
      }
      let AllData = {
        auditMark: 2, // 审核标志, 1 已审核,2 未审核
        bookkeepingMark: 2, // 记账标志 , 1 已记账 , 2 未记账
        inOutCategoryIdentification: 4, // 入库、出库类别标识, 1-6 采购入库、产成品入库、销售出库、生产材料出库、基建出库、其他出库
        inOutIdentification: 2, // 入库、出库标识，1 入库，2 出库
        deptId: this.Form.deptId, //部门id
        document: this.Form.document, // 单据号
        documentDate: moment(this.Form.document_date).format("YYYY-MM-DD"), // 单据日期
        balance: moment(this.Form.balance).format("YYYY-MM-DD"), // 审核日期

        supplier: this.Form.supplierId, // 供应商
        finishedProductDepot: this.Form.finishedProductDepotId, // 产成品仓库
        sendReceiveType: this.Form.sendReceiveTypeId, // 收发类型Id

        responsiblePerson: this.Form.responsiblePersonId, // 负责人Id
        inspector: this.Form.inspectorId, // 审核人(传userid)
        singleProducer: this.Form.singleProducerId, // 制单人(传userid)
        warehouseObjectInformationEntities: array,

        pkCorp: this.Form.pk_corpId, //公司Id
        cwhsmanagerid: this.Form.cwhsmanagerid, //库管员
        pkCalbody: this.Form.pk_calbodyId, //库存组织
        farmer: this.Form.farmerId, //农户
        ownedBranch: this.Form.ownedBranchId, //所属分厂
        picker: this.Form.pickerId, //所属分厂
        finishedProductType: this.Form.finishedProductType, //产成品分类
      };
      console.log("this.Form", this.Form);

      console.log("全部的数据", AllData);
      comHttp.addInOrOutStorageOrderAndGoods(AllData).then((res) => {
        console.log("返回的信息为:::::", res);
        if (res.success == true) {
          this.$message.success("提交成功");
          this.saveGoodsShelvesInfo(res.result.list);
          this.Reset();
        } else {
          this.$message.error("提交失败");
        }
      });
    },
    // 保存货架信息
    saveGoodsShelvesInfo(data) {
      let array = [];
      for (let i = 0; i < data.length; i++) {
        let submitData = {
          objectId: data[i].id,
          positionId: this.DataSource[i].position,
          inOutShelf: this.DataSource[i].goodsShelves.split(","),
          isOut: 1,
        };
        array.push(submitData);
      }
      console.log("提交数据", array);
      comHttp.saveShelfInfo(array).then((res) => {
        console.log("213", res);
      });
    },
    // ---------  写好的 --------------
    // 获取单号
    getApplyOrder() {
      let queryPath = "?string=SCCK-";
      comHttp.getOrder(queryPath).then((res) => {
        this.Form.document = res.message;
      });
    },

    // 设置所属仓库, 上面表单触发事件
    setdataSourcestorageUnit(value, option) {
      let array = value.split("|");
      this.Form.storageUnit = array[1];
      // console.log(array[0]);
      let key = option.key;
      console.log(key);
      // option.key
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].storageUnitNo = array[0];
        this.DataSource[i].storageUnit = array[1];
        this.DataSource[i].storageUnitId = option.key;
      }
      console.log("赋值好的表格内容:::::", this.DataSource);
    },
    // 表单仓库点击按钮 -------- 上方选择仓库后，下方物品都填入该仓库
    setdataSourceDepartment(value, option) {
      let array = value.split("|");
      console.log(array[0]);
      this.Form.depotNo = array[0];
      this.Form.depotName = array[1];
      let key = option.key;
      // 获取物品信息列表,根据仓库编码
      // let goodsList = this.getGoodSInfo(key);

      // option.key
      // 根据仓库查询物品信息,并存储到相应的物品信息表中
      for (let i = 0; i < this.DataSource.length; i++) {
        this.DataSource[i].depotNo = array[0];
        this.DataSource[i].depotName = array[1];
        this.DataSource[i].depotId = key;

        this.DataSource[i].goodsList = this.goodsList;
      }
      console.log("赋值好的表格内容:::::", this.DataSource);
    },
    // 获取供应商列表
    getSupplierInfo() {
      comHttp.getSupplierInfo().then((res) => {
        console.log("供应商列表-》》》", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            supplierId: res.result[i].id,
            suppilerCode: res.result[i].suppilerCode,
            suppilerName: res.result[i].suppilerName,
          };
          this.supplierList.push(data);
        }
      });
    },
    // 获取供应商信息
    getSupplierId(value, option) {
      let array = value.split("|");
      this.Form.supplier = array[1]; //供应商名称
      this.Form.supplierCode = array[0]; //供应商编码
      this.Form.supplierId = option.key;
      console.log("供应商Id:", this.Form.supplierId);
    },

    // 设置存货列表
    async setGoodsList(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      let array = target.depotNo.split("|");
      target.depotNo = array[0]; // 仓库编码
      target.depotName = array[1]; // 仓库名称

      let SotrageInfo = this.storageList.filter(
        (item) => item.depotNo === array[0]
      )[0];
      target.depotId = SotrageInfo.depotId;

      // 仓库Id
      console.log("仓库Id:::", target.depotId);
      // 设置好存货
      // let goodsList = this.getGoodSInfo(target.depotId);
      target.goodsList = this.goodsList;
      console.log("存货列表:::", target.goodsList);
      // 设置好仓位
      let positionList = await this.getPositionList(target.depotId);
      console.log("positionListpositionList===>", positionList);
      let TempList = await this.disableParent(positionList);
      target.positionList = TempList;
      console.log("仓位列表:::", target.positionList);
    },

    // 获取产成品分类Id
    getFinishGoodsTypeId(key) {
      let target = this.DataSource.filter((item) => item.key === key)[0];
      console.log("item.dataType--------->", target);
      // let array = [];
      // array = target.finishedProductType.split("|");
      // target.finishedProductTypeId = parseInt(array[0]);
      // target.finishedProductType = array[1];
      // console.log("产成品分类ID", target.finishedProductTypeId);
    },
    // 删除
    Delete(id) {
      comHttp.deleteInOrOutStorageGoods("?id=" + id).then((res) => {
        if (res && res.code === 200) {
          this.$message.success("删除成功");
          this.setInitInfo(this.$route.query.Id);
        } else {
          this.$message.error("删除失败");
        }
      });
    },

    // 禁用父节点
    disableParent(Tree) {
      return new Promise((resolve) => {
        if (Tree != null) {
          Tree.forEach((item) => {
            console.log("55555", item);
            if (item.children.length != 0) {
              item[`disabled`] = true;
            } else {
              this.disableParent(item.children);
            }
          });
        }
        resolve(Tree);
      });
    },

    // 获取仓位列表
    getPositionList(id) {
      console.log(id, 55555555555);
      let positionList = [];
      return new Promise((resolve) => {
        comHttp.getPositionInformationListByDepotId("?id=" + id).then((res) => {
          console.log("获取仓位列表", res);
          if (res.result.length != 0) {
            positionList = res.result[0].children;
            resolve(positionList);
          } else {
            let falseTag = 1;
            resolve(falseTag);
          }
        });
      });
    },

    // 获取批次号
    getBatchNumberList(id1, id2, id3 = "") {
      let temp = [];
      return new Promise((resolve) => {
        comHttp
          .getgetBatchNumberById(
            "?depotId=" + id1 + "&inventoryId=" + id2 + "&position=" + id3
          )
          .then((res) => {
            temp = res.result;

            resolve(temp);
          });
      });
    },
    onChangeBumen(a) {
      console.log("a", a);
      let array = a.split("|");
      this.Form.deptId = array[0];
      this.Form.deptIdName = array[1];
      console.log("部门名称deptIdName", this.Form.deptIdName);
      console.log("部门iddeptId", this.Form.deptId);
    },
    // 获取源单数据
    async getOriginData(data) {
      console.log("传递过来的数据:::::", data);
      this.DataSource = [];
      this.form = data;
      // 默认信息
      //  this.Form.document=""; // 单据日期
      // this.Form.document_date= moment().format("YYYY-MM-DD"), // 单据日期
      // this.Form.pk_corp = "山东七河生物科技股份有限公司";
      // this.Form.pk_corpId = "1001";
      // this.Form.pk_calbodyId = "1001F3100000000002LS"; //库存组织ID
      // this.Form.pk_calbody = "山东七河生物"; //库存组织名称
      // this.Form.pkCalbody_dictText = data.ccalbodyid_dictText; // 库存组织
      // 仓库名称
      this.Form.depotName = data.goodsList[0].depotId_dictText;
      this.Form.depotId = data.goodsList[0].depotId;
      // 产成品仓库
      this.Form.finishedProductDepot = data.finishedProductDepot_dictText;
      this.Form.finishedProductDepotId = data.finishedProductDepot;
      // 产成品分类
      this.Form.finishedProductType = data.finishedProductType;
      this.Form.finishGoodsType = data.finishedProductType_dictText;
      // 领料员
      this.Form.pickerId = data.applicant;
      this.Form.picker = data.applicant_dictText;
      // 所属分厂
      this.Form.ownedBranchId = data.ownedBranch;
      this.Form.ownedBranch = data.ownedBranch_dictText;
      // this.DataSource = newData;
      // console.log("this.DataSource", this.DataSource);
      this.Form.deptId = data.applicationDept;
      this.Form.deptIdName = data.applicationDept_dictText; // 部门
      // 获取仓位、库位列表
      let positionList = await this.getPositionList(data.applicationDepot);
      console.log("log positionList==>", positionList);
      if (positionList != 1) {
        let TempList = await this.disableParent(positionList);
        positionList = TempList;
      }
      for (let i = 0; i < this.form.goodsList.length; i++) {
        let data = {
          key: i + 1,
          id: this.form.id, //
          depotId: this.form.goodsList[i].depotId, //仓库id
          depotNo: this.form.goodsList[i].depotIdBac_dictText, //仓库编码
          depotName: this.form.goodsList[i].depotId_dictText, //仓库名称
          positionList: positionList,
          pickingContentId: this.form.goodsList[i].id, //货架
          // tempArr[i].pickingContentId = data1[i].id; //生产领料表单物品ID
          inventoryId: this.form.goodsList[i].inventoryId, //存货id
          inventoryNo: this.form.goodsList[i].inventoryNo, //存货编码
          inventoryName: this.form.goodsList[i].invname, //名称
          standardModel: this.form.goodsList[i].invspec, //规格型号
          unit: this.form.goodsList[i].measname, //单位
          batchNumber: "null",
          quantity: this.form.goodsList[i].actualQuantity,
          unitPrice: "", //单价
          money: "", //金额
          // positionList: [],
          position: "",

          sourceNumber: this.form.goodsList[i].requisitionNo, //源单号
          deliveryDate: this.Form.document_date,
          remark: "", // 备注
          goodsShelves: "", // 货架
        };
        let getActualQuantity = {
          depotId: this.form.depotId, //仓库
          inventoryId: this.form.goodsList[i].inventoryId,
          sourceNumber: this.form.requisitionNo,
        };

        // await => promise
        this.getActualQuantityList(getActualQuantity).then((res) => {
          data["actualQuantity"] = res;
        });

        let getNumberData = {
          depotId: this.form.depotId,
          inventoryId: this.form.goodsList[i].inventoryId,
        };
        data["existingQuantity"] = await this.getTotalGoods(getNumberData);

        this.DataSource.push(data);
      }
    },

    /*  async getOriginData(data) {
      this.DataSource = [];
      let dataSource = [];
      console.log("传来的数据data", data);
      // 仓库名称
      this.Form.depotName = data.goodsList[0].warehouse;
      this.Form.depotId = data.goodsList[0].depotId;
      // 产成品仓库
      this.Form.finishedProductDepot = data.finishedProductDepot_dictText;
      this.Form.finishedProductDepotId = data.finishedProductDepot;
      // 产成品分类
      this.Form.finishedProductType = data.finishedProductType;
      this.Form.finishGoodsType = data.finishedProductType_dictText;
      // 领料员
      this.Form.pickerId = data.applicant;
      this.Form.picker = data.applicant_dictText;
      // 所属分厂
      this.Form.ownedBranchId = data.ownedBranch;
      this.Form.ownedBranch = data.ownedBranch_dictText;
      // this.DataSource = newData;
      // console.log("this.DataSource", this.DataSource);
      this.Form.deptId = data.applicationDept;
      this.Form.deptIdName = data.applicationSector; // 部门

      console.log("data", data);

      let tempArr = [];
      let data1 = data.goodsList;
      console.log("data1", data1);
      tempArr = data1;
      for (let i = 0; i < data1.length; i++) {
        // tempArr[i].pickingContentId = data1[i].id; //生产领料表单物品ID
        tempArr[i].key = i + 1;
        tempArr[i].storageUnitId = data1[i].affiliationId;
        tempArr[i].storageUnit = data1[i].affiliation;
        tempArr[i].depotId = data1[i].depotId;
        tempArr[i].depotNo = data1[i].depotNo;
        tempArr[i].depotName = data1[i].warehouse;
        tempArr[i].depotLocation = data1[i].depotLocation;

        this.$set(tempArr[i], "position", "");

        tempArr[i].inventoryId = data1[i].inventoryId;
        tempArr[i].inventoryNo = data1[i].Number;
        // tempArr[i].Number = data[i].Number;
        tempArr[i].inventoryName = data1[i].goodName;
        tempArr[i].standardModel = data1[i].standard;
        tempArr[i].unit = data1[i].unit;
        tempArr[i].quantity = data1[i].number2;
        tempArr[i].price = data1[i].price;
        tempArr[i].money = data1[i].price;
        tempArr[i].finishedProductType = data1[i].finishGoodsType;
        tempArr[i].remark = data1[i].remark;
        tempArr[i].deliveryDate = this.Form.document_date; //出库日期=单据日期
        tempArr[i].applicationDept = data1[i].applicationDept; //部门
        tempArr[i].applicationSector = data1[i].applicationSector; //部门

        // console.log("tempArr", tempArr);
        // this.DataSource = tempArr;

        tempArr[i].remark = "";
        tempArr[i].goodsShelves = ""; //货架
        tempArr[i].pickingContentId = data1[i].id; //货架
        // 获取仓位、库位列表
        let positionList = await this.getPositionList(data1[i].depotId);
        console.log("positionList", positionList);
        if (positionList != 1) {
          if (positionList != null && positionList != "null") {
            let TempList = await this.disableParent(positionList);
            tempArr[i].positionList = TempList;
          } else {
            tempArr[i].positionList = [];
          }
        }

        // 获取批次号列表
        if (tempArr[i].position == "null" || tempArr[i].position == undefined) {
          // tempArr[i].position = "";
          tempArr[i].BatchList = await this.getBatchNumberList(
            data1[i].depotId,
            data1[i].inventoryId
          );
        } else {
          // 获取批次号列表
          tempArr[i].BatchList = await this.getBatchNumberList(
            data1[i].depotId,
            data1[i].inventoryId,
            data1[i].position
          );
        }
        // 获取计算好的实时数量
        let tempData = {
          inventoryId: data1[i].inventoryId,
          inventoryNo: data1[i].depotNo,
          sourceNumber: data1[i].sourceNumber,
        };
        comHttp.getQuantityUnfinishedGoods(tempData).then((res) => {
          // console.log("res==============>", res);
          this.randomKey = Math.random();
          // this.$set(tempArr[i], existingQuantity, res.result.balance);
          tempArr[i].existingQuantity = res.result.balance;
          // console.log(
          //   "tempArr[i].existingQuantity",
          //   tempArr[i].existingQuantity
          // );
        });
        dataSource.push(tempArr[i]);
      }
      // console.log("tempData", tempData);
      this.DataSource = dataSource;
      // this.DataSource = this.DataSource.concat(tempArr);
      console.log("this.DataSource=====!!!!!!!", this.DataSource);
    }, */
    // 获取存货数量
    async getTotalGoods(data) {
      console.log("验证信息111111111111", data);
      return new Promise((resolve) => {
        comHttp.getTotalGoods(data).then((res) => {
          console.log("存货数量111111111", res);
          if (res.result.balance == null || res.result.balance == "null") {
            resolve(0);
          } else {
            resolve(res.result.balance);
          }
          // resolve(res.result.balance);
        });
      });
    },
    async getActualQuantityList(data) {
      console.log("验证信息222222222222", data);
      return new Promise((resolve) => {
        comHttp.getStockNoticeGoodsList(data).then((res) => {
          console.log("现存数量", res);
          if (res.result.balance == null || res.result.balance == "null") {
            resolve(0);
          } else {
            resolve(res.result.balance);
          }
        });
      });
    },
  },
};
</script>

<style></style>
